<?php
session_start();
include_once('helpers.php');
include_once('db.php');
include_once('Employee.php');

$id = intVal($_REQUEST['id']);
if($id){
	try{
		$employee = Employee::get($id);
	}catch(Exception $e){
		$_SESSION['msg'][] = $e->getMessage();
		_notFound();
	}
	if($_REQUEST['act']=="edit" && !$_POST){
		$employee = $employee->editMode();
	}else{
		if($_REQUEST['act']=="delete"){
			try{
				$employee->delete();
				_forward("index.php");
			}catch(Exception $e){
				$_SESSION['msg'][] = $e->getMessage();
				_conflict();
			}
		}
	}
}
else{
	$employee = new Employee();
}

if($_POST){
	$_employee = $_POST['Employee'];
	$employee->name 	= $_employee['name'];
	$employee->gender 	= $_employee['gender'];
	try{
		if(!$employee->id){
			$edit = true;
		}else{
			//Force 0
			$employee->editMode = 0;
		}
		$employee->save($_employee['token']);
		_forward("index.php");

	}catch(Exception $e){
		echo $e->getMessage();
		_d("Updated Data:");
		_d(Employee::get($employee->id));
	}
}

$employees = Employee::getAll();

if($errs = _getErrors()){
	_d($errs);
}
?>
<!doctype html>
<html>
	<head>
		<link href="styles.css" type="text/css" rel="stylesheet" />
	</head>
	<body>
		<form action="<?=$_SERVER['REQUEST_URI']?>" method="post">
			<div><input type="hidden" name="Employee[token]" value="<?=$employee->token?>"/></div>
			<table>
			<tr>
				<td>Name: </td><td><input type="text" name="Employee[name]" value="<?=$employee->name?>"/></td>
			</tr>
			<tr>
				<td>Gender:</td>
				<td><select name="Employee[gender]"><?=_options(array("Male"=>"Lalaki", "Female"=>"Babae"), $employee->gender)?></select></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="<?=($employee->id)?"Update":"Save"?>"/></td>
			</table>
		</form>
		<br />
		<table>
			<thead>
				<tr>
					<th>Name</th>
					<th>Gender</th>
					<th>ETA Delete</th>
				</tr>
			</thead>
			<tbody>
		<?php if($employees):?>
			<?php foreach($employees as $emp):?>
				<tr>
					<td><?=$emp->name?></td>
					<td><?=$emp->gender?></td>
					<td><?=$emp->estimatedTimeToAllowDelete()?></td>
					<td><a href="<?=$emp->editUrl();?>">Edit</a>
						&middot; <a href="<?=$emp->deleteUrl();?>">Delete</a>
					</td>
				</tr>
			<?php endforeach;?>
		<?php endif;?>
			</tbody>
		</table>
	</body>
</html>